package cn.sinjet.model.carassist;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

//import com.amap.navi.BaiduTTSModel;
import com.amap.navi.NaviModel;
import com.mgroup.wazehelper.R;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.communication.bluetooth.BluetoothModel;
import cn.sinjet.entity.AppInfo;
import cn.sinjet.model.carsystem.CarModel;
import cn.sinjet.model.mcuupgrade.McuUpgradeModel;
import cn.sinjet.model.mcuupgrade.McuUpgradeModelSimple;
import cn.sinjet.prototol.codec.ToureDevCodec;
import cn.sinjet.utils.HttpUtils;
import cn.sinjet.utils.SharedPreferenceUtil;
import cn.sinjet.viewmodel.PageDefine;
import cn.sinjet.viewmodel.ViewModel;

enum enumUpLoadToService{
	enumUpLoadToServiceAgencyCode,
	enumUpLoadToServiceModuleCode,
	enumUpLoadToServiceModuleVersion,
	enumUpLoadToServiceLocation,
	enumUpLoadToServiceMax
}

/*
 * @author: Sinjet Navigation Model 
 */
@SuppressLint("DefaultLocale")
@SuppressWarnings("deprecation")
public class AppModel{
	private static AppModel instance = null;
	private static String tag = "navi";
    private Context mContext = null;
    
//    MainModel  models;
    private Settings mSettings = new Settings();
    
	private PowerManager powerManager = null;
	private WakeLock wakeLock = null;
	
    private List<AppInfo> mAppInfos = null;
//    private DoorOpenWarningView mDoorWarning;
    public static AppModel getInstance(){
    	if(instance == null)
    		instance = new AppModel();
    	return instance;
    }
        
    public AppModel(){
    }
    
    public void init(Context context) {
		// TODO Auto-generated method stub
//		Log.i(tag,"restore data");
    	mContext = context;
    	if(mContext == null){
    		Log.i(tag, "ERRRRRRRRRRRRRRRRRRRRRRR");
    		return;
    	}
    	
    	powerManager = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
		wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Sinjet Lock");
		//是否需计算锁的数量
		wakeLock.setReferenceCounted(false);
//    	TTSController.getInstance(mContext).init();// 初始化语音模块
    	
		restoreSettingData();
		restoreAppData();
		mSettings.initUI();
		displayBearing(0.0f);
		if(mSettings.isKeepScreenOn) wakeLock.acquire();
		else if(wakeLock.isHeld()) wakeLock.release();
	}
	
	public void deInit(){
		if(wakeLock.isHeld()) wakeLock.release();
		storeAppData();
		storeSettingData();
	}    
    
	
	/*public void onDoorState(Context context,int leftFront,int rightFront,int leftRear,int rightRear,int trunk){
		if(mDoorWarning == null && context != null)
			mDoorWarning = new DoorOpenWarningView(context,R.style.CustomDialog);
		if(mDoorWarning != null)
		mDoorWarning.showOsdView(leftFront, rightFront, leftRear, rightRear, trunk);
	}*/
    public Settings getSettings(){
    	if(mSettings == null)
    		return new Settings();	
    	return mSettings;
    }
    
    AppInfo mAppInfo = null;
    
    public void selectNewApp(int key,AppInfo appInfo){
 	  if(mAppInfos == null) mAppInfos = new ArrayList<AppInfo>();
    	  mAppInfo = appInfo;
    	  mAppInfos.add(mAppInfo);
    	  
//    	  storeAppData(mContext);
    }
    public AppInfo getNewApp(){
       return mAppInfo;	
    }
    
    public void restoreAppData(){
    	try{
	    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
	    	   mAppInfos = util.getAppInfoList();
	    	   if(mAppInfos == null) //first launch
	    		   mAppInfos = new ArrayList<AppInfo>();
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
    }
    
    public void storeAppData(){
    	try{
	    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
	    	   util.setAppInfoList(mAppInfos);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    }
    }
    
    
    
    public void restoreSettingData(){
    	try{
    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
    	   mSettings.restoreSettings(util.getSp());
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    
    public void storeSettingData(){
    	Log.i(tag, "storeSettingData");
    	try{
    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
    	   mSettings.storeSettings(util.getEditor());
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    
    public void getMessage(byte[] message){
    	 //
    	 
    }

    
	public int getDayNightMode() {
		return getSettings().dayNightMode;
	}
	
	public int getDayOrNight(){
		  if(getSettings().dayNightMode == 0){//if it is autoMode
			    long time = System.currentTimeMillis();
			    final Calendar calendar = Calendar.getInstance();
			    calendar.setTimeInMillis(time);
			    int hour = calendar.get(Calendar.HOUR_OF_DAY);
//			    int minute = calendar.get(Calendar.MINUTE);
//			    Log.i("test","get time: "+hour+"h"+minute+"m");
			    if(hour >= 6 && hour < 18)
			    	return 1;
			    else 
			    	return 2;
		  }else{
		       return getSettings().dayNightMode;
		  }
	}

	public void setDayNightMode(int dayNightMode) {
		getSettings().dayNightMode = dayNightMode;
	}

	/*public int getHeadMode() {
		return headMode;
	}*/

/*	public void setHeadMode(int headMode) {
		this.headMode = headMode;
	}*/

	public boolean isTrafficVoiceOn() {
		return getSettings().isTrafficVoiceOn;
	}

	public void setTrafficVoiceOn(boolean isTrafficVoiceOn) {
		getSettings().isTrafficVoiceOn = isTrafficVoiceOn;
	}

	
	public boolean isKeepScreenOn() {
		return getSettings().isKeepScreenOn;
	}

	public void setKeepScreenOn(boolean isKeepScreenOn) {
		getSettings().isKeepScreenOn = isKeepScreenOn;
	}

	
	int mOldSpeed = 0;
	protected void displaySpeed(float speed) {
		// TODO Auto-generated method stub
		Log.i("test", "get gps Speed:"+speed);
		if(BluetoothModel.getInstance().isConnected()) return;
		if(speed >=0.0f && speed <=240.0f){
			int speedDegree = (int)speed;
			if(mOldSpeed == speedDegree) return;
			mOldSpeed = speedDegree;
			ViewModel.getIns().setViewProperty(R.id.meter_speed_meter, speedDegree);
			ViewModel.getIns().setViewProperty(R.id.meter_speed_value, String.valueOf(speedDegree));
		}
	}
	
	int mOldWhich = -1;
	protected void displayBearing(float bearing) {
		 Log.i("test", "onGetBearing:"+bearing);
		// TODO Auto-generated method stub
		if (bearing < 0 || bearing > 360.0f)
		    return;
 
		float fWhich = (bearing / (360.0f / 16));
		int iWhich = (int)(fWhich+0.999f);
		iWhich = iWhich / 2;
		if(iWhich <0 || iWhich >7) iWhich = 0;
		
		if(mOldWhich == iWhich) return;
		mOldWhich = iWhich;
		String[] strDirection = new String[]{"北","东北","东","东南","南","西南","西","西北"};
//        ViewModel.getIns().setViewProperty(R.id.meter_direction_value, strDirection[iWhich]);
	}


	

	
	

	public void onClkBTStateHint() {
		// TODO Auto-generated method stub
		if(!BluetoothModel.getInstance().isConnected())
			BluetoothModel.getInstance().connectBT();
	}
	
	public void onBackToMyScreen(){
//		BluetoothModel.getInstance().tryToKeepConnected();
	}
	
	private Handler mHandlerUpdate = new Handler();
	
	Runnable mUpdateTime = new Runnable() {
      		
		@Override
		public void run() {
			// TODO Auto-generated method stub
           updateTimeView();
           mHandlerUpdate.postDelayed(mUpdateTime,10000);
		}
	}; 
	
	private void updateTimeView(){
		Log.i("test", "updateTimeView");
		long time = System.currentTimeMillis();
	    final Calendar calendar = Calendar.getInstance();
	    calendar.setTimeInMillis(time);
	    int hour = calendar.get(Calendar.HOUR_OF_DAY);
	    int minute = calendar.get(Calendar.MINUTE);
	    String strTime = String.format("%02d:%02d", hour,minute);
	    ViewModel.getIns().setViewProperty(R.id.meter_time, strTime);
	}
	public void onLeavePage(int leavePage) {
		// TODO Auto-generated method stub
		switch(leavePage){
		case PageDefine.PAGE_CAR_METER:
			mHandlerUpdate.removeCallbacks(mUpdateTime);
			break;
		}
	}
	
	ToureDevCodec toureCodec = new ToureDevCodec();
	public void onEnterPage(int pageId){
		Log.i(tag, "onPageResume:" +pageId);
//		 onBackToMyScreen();
		switch(pageId){
		case PageDefine.PAGE_CAR_CONDITION:
			toureCodec.sendAppPage(0x01);
			break;
		case PageDefine.PAGE_FAST_DETECT:
			toureCodec.sendAppPage(0x03);
			break;
		case PageDefine.PAGE_CAR_ERR_DETECT:
			toureCodec.sendAppPage(0x02);
		   break;
		case PageDefine.PAGE_HOME:
		case PageDefine.PAGE_NAVI_SELECT:
			toureCodec.sendAppPage(0x04);
//			models.hudModel.setNaviRunning(0);
			Log.i(tag, "on enterPageHome:"+CarModel.getInstance().isFirstEnter());
			if(CarModel.getInstance().isFirstEnter()){
				CarModel.getInstance().setFirstEnter(false);
				CarModel.getInstance().startVersionCheck(false);
	    	}
			break;
		case PageDefine.PAGE_CAR_METER:{
			 toureCodec.sendAppPage(0x00);
			 mHandlerUpdate.postDelayed(mUpdateTime,500);  
		  }
			break;
		
		case PageDefine.PAGE_ABOUT:
			//get app-version and display
			String version = "V1.0";
			try {
				PackageInfo packInfo = mContext.getPackageManager().getPackageInfo(
						mContext.getPackageName(), 0);
				version = packInfo.versionName;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			ViewModel.getIns().setViewProperty(R.id.app_version, mContext.getResources().getString(R.string.app_version)+ version);
			McuUpgradeModel.getInstance().checkVersion();
			break;
		}
	}
	
	
	
	public void onClkView(int tag){
		switch(tag){	
		/*case R.id.set_navi_strategy:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_NAVI_STRATEGY);
			break;
		case R.id.navi_strategy_back:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_NAVI_SELECT);
			NaviModel.getInstance().requestCalculateRoute(ViewModel.getIns().getCurContext());
			break;
		case R.id.navi_strategy_avoid_highspeed:
		case R.id.navi_strategy_congestion:
		case R.id.navi_strategy_highspeed:
		case R.id.navi_strategy_cost:
			onClkStrategy(tag);
		    break;*/

		case R.id.car_condition_queryerr:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_ERR_QUERY);
			break;


		case R.id.car_meter_meter_tab:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_CAR_METER);
			break;

		case R.id.navi_setting_back:
			ViewModel.getIns().finishActivity();
			break;
		case R.id.set_navi_back:
		case R.id.phone_calllog_back:
		case R.id.phone_contact_back:
			Log.i("page", "on setting back");
			ViewModel.getIns().jumpPage(PageDefine.PAGE_HOME);
			break;
		case R.id.setting_general_tab:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SETTING_GENERAL);
			break;
	/*	case R.id.setting_navi_tab:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SETTING_NAVI);
			break;*/
//		case R.id.my_favor:
//			ViewModel.getIns().jumpPage(PageDefine.PAGE_HOME);
//			break;
		/*case R.id.virtual_light:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_SCREEN_OFF);
			break;
		case R.id.virtual_home:
			if(ViewModel.getIns().getCurPage() != PageDefine.PAGE_HOME)
			       ViewModel.getIns().jumpPage(PageDefine.PAGE_HOME);
			else{
				ViewModel.getIns().setViewProperty(R.id.viewPager);
			}
			break;*/
/*		case R.id.virtual_mute:
		   onMuteApp();
			break;*/
		case R.id.screen_off_turn_on:
			ViewModel.getIns().jumpToPreviewPage();
			break;
		case R.id.setting_menu_general:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_SETTING_GENERAL);
			break;
		case R.id.setting_menu_navi:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_SETTING_NAVI);
			break;
		case R.id.setting_menu_hud:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_HUD_SET);
			break;
		case R.id.setting_about_us:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_ABOUT);
			break;
		case R.id.setting_introduction:
			//ViewModel.getIns().jumpPage(PageConstant.PAGE_CONTACT_US);
			Uri uri = Uri.parse("http://www.sinjet.cn/axw_view.asp?id=372");
			Intent it = new Intent(Intent.ACTION_VIEW, uri);
			ViewModel.getIns().getCurContext().startActivity(it);
			break;
		case R.id.car_condition_fullcheck:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_FAST_DETECT);
			break;
		case R.id.setting_exit_system:
			SinjetApplication.getInstance().exit();
			break;
		case R.id.system_err_check:
		case R.id.system_power_supply:
		case R.id.system_air_intake:
		case R.id.system_idling:
		case R.id.system_cooling:
		case R.id.system_memissions:
		case R.id.system_vin_code:
//			ViewModel.getIns().jumpPage(PageConstant.PAGE_CAR_CONDITION_DETAIL);
			onClkCondictionItem(tag);
			break;
		case R.id.obd_discription_back:
			ViewModel.getIns().jumpToPreviewPage();
			break;
		case R.id.car_vin_code_back:
		case R.id.err_detect_system_back:
		case R.id.car_full_check_back:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_CAR_CONDITION);
			break;
			
		case R.id.about_us_back:
		case R.id.contact_us_back:
			ViewModel.getIns().jumpPage(PageDefine.PAGE_SETTING_GENERAL);
			break;
		case R.id.version_check:
			CarModel.getInstance().startVersionCheck(true);
			break;
		case R.id.bt_auto_open:
			mSettings.bAutoOpenBT = !mSettings.bAutoOpenBT;
			ViewModel.getIns().setViewProperty(tag, (int)((mSettings.bAutoOpenBT)?1:0));
			break;
    	case R.id.gps_auto_open:
    		mSettings.bAutoOpenGps = !mSettings.bAutoOpenGps;
    		ViewModel.getIns().setViewProperty(tag, (int)((mSettings.bAutoOpenGps)?1:0));
    		break;
    	case R.id.keep_screen_on:
    		mSettings.isKeepScreenOn = !mSettings.isKeepScreenOn;
    		ViewModel.getIns().setViewProperty(tag, (int)((mSettings.isKeepScreenOn)?1:0));
    		if(mSettings.isKeepScreenOn) wakeLock.acquire();
    		else if(wakeLock.isHeld()) wakeLock.release();
    		//if(MainModel.getIns().naviModel.getSettings().isKeepScreenOn)
				//getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    		break;
    	case R.id.simple_navi_set_back:
    		ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SIMPLE_NAVI);
    		break;
    	case R.id.navi_set_route_detail:
    		ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_ROUTE_DETAIL);
    		break;
    	case R.id.navi_set_day_night_mode:
    		ViewModel.getIns().refreshView(R.id.navi_set_day_night_mode);
    		break;
    	case R.id.navi_set_traffic_voice:
    		setTrafficVoiceOn(!isTrafficVoiceOn());
    		ViewModel.getIns().setViewProperty(tag, (int)((isTrafficVoiceOn())?1:0));
    		break;
    	case R.id.navi_set_navi_voice:
    		AppModel.getInstance().getSettings().isNaviVoiceOn = !AppModel.getInstance().getSettings().isNaviVoiceOn;
    		int checked = (AppModel.getInstance().getSettings().isNaviVoiceOn)?1:0;
    		ViewModel.getIns().setViewProperty(tag,checked);
    		break;
    	case R.id.fast_detect_start:
    		Log.i("test", "send fast detect");
//    		ViewModel.getIns().setViewVisible(R.id.scan_car_view_parent, 2);
//    		ViewModel.getIns().setViewProperty(R.id.scan_car_view,1);
    		toureCodec.sendStartFastDetect();
    		break;
    	case R.id.check_mcu_version:
    		Log.i("test", "on click mcu_version");
			if (1 == CarModel.getInstance().devModule.getMCUUpgradeMethod())
			{
				McuUpgradeModel.getInstance().startUpgrade();
			}
			else if (2 == CarModel.getInstance().devModule.getMCUUpgradeMethod())
			{
				McuUpgradeModelSimple.getInstance().startUpgrade();
			}
    		break;
    	/*case R.id.set_home_address:
    		NaviModel.getInstance().onClkSetHomeAddress();
    		break;
    	case R.id.set_office_address:
    		NaviModel.getInstance().onClkSetOfficeAddress();
    		break;*/
    	case R.id.setting_voice_alarm:
    		onClkSettingVoiceAlarm();
    		break;
    	case R.id.safety_voice_play:
    		onClkTryPlaySafetyAlarm();
    		break;
    	case R.id.car_anormal_play:
    		onClkTryPlayCarAnormal();
    		break;
    	case R.id.temperature_voice_on:
    		onClkTemperatureVoiceOn();
    		break;
    	case R.id.voltage_voice_on:
    		onClkVoltageVoiceOn();
    		break;
    	case R.id.tpms_voice_on:
    		onClkTpmsVoiceOn();
    		break;
    	case R.id.handbrake_voice_on:
    		onClkHandbrakeVoiceOn();
    		break;
    	case R.id.seatbelt_voice_on:
    		onClkSeatbeltVoiceOn();
    		break;
    	case R.id.doors_voice_on:
    		onClkDoorVoiceOn();
    		break;
		}
	}
    void onClkTemperatureVoiceOn(){
    	getSettings().mTempVoiceOn = (getSettings().mTempVoiceOn==1)?0:1;
    	ViewModel.getIns().setViewProperty(R.id.temperature_voice_on, getSettings().mTempVoiceOn);
    }
    void onClkVoltageVoiceOn(){
    	getSettings().mVoltageVoiceOn = (getSettings().mVoltageVoiceOn==1)?0:1;
    	ViewModel.getIns().setViewProperty(R.id.voltage_voice_on, getSettings().mVoltageVoiceOn);
    }
    void onClkTpmsVoiceOn(){
    	getSettings().mTpmsVoiceOn = (getSettings().mTpmsVoiceOn==1)?0:1;
    	ViewModel.getIns().setViewProperty(R.id.tpms_voice_on, getSettings().mTpmsVoiceOn);
    }
    void onClkHandbrakeVoiceOn(){
    	getSettings().mHandbrakeVoiceOn = (getSettings().mHandbrakeVoiceOn==1)?0:1;
    	ViewModel.getIns().setViewProperty(R.id.handbrake_voice_on, getSettings().mHandbrakeVoiceOn);
    }
	void onClkSeatbeltVoiceOn(){
		getSettings().mSeatbeltVoiceOn = (getSettings().mSeatbeltVoiceOn==1)?0:1;
		ViewModel.getIns().setViewProperty(R.id.seatbelt_voice_on, getSettings().mSeatbeltVoiceOn);
	}
	void onClkDoorVoiceOn(){
		getSettings().mDoorVoiceOn = (getSettings().mDoorVoiceOn==1)?0:1;
		ViewModel.getIns().setViewProperty(R.id.doors_voice_on, getSettings().mDoorVoiceOn);
	}
	
	int safetyAlarmPlayingIndex = -1;
	void onClkTryPlaySafetyAlarm(){
	     String[] alarmText = new String[]{"请系好安全带","请放下手刹","左前门没有关","多个门没有关"};
	     safetyAlarmPlayingIndex++;
	     if(safetyAlarmPlayingIndex>=alarmText.length)
	    	 safetyAlarmPlayingIndex = 0;
	     //BaiduTTSModel.getInstance(mContext).playText(alarmText[safetyAlarmPlayingIndex]);
	}
	int anormalAlarmPlayingIndex = -1;
	void onClkTryPlayCarAnormal(){
		String[] alarmText = new String[]{"水温偏高","电瓶电压偏低","左前轮欠压"};
		anormalAlarmPlayingIndex++;
		if(anormalAlarmPlayingIndex >= alarmText.length)
			anormalAlarmPlayingIndex = 0;
		
		//BaiduTTSModel.getInstance(mContext).playText(alarmText[anormalAlarmPlayingIndex]);
	}
	
	private void onClkSettingVoiceAlarm(){
		ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_VOICE_ALARM_SET);
	}
	
	
	private void onClkCondictionItem(int id){
		String title = "";
		String subTitle = "";
		String normalRange = "";
		String curValue = "";
		String knowledge = "";
		int toPageId = PageDefine.PAGE_CAR_CONDITION_DETAIL;
		switch(id){
		case R.id.system_err_check:
			title = "故障检测系统";
			toPageId = PageDefine.PAGE_CAR_ERR_DETECT;
			break;
		case R.id.system_power_supply:
			title = "电源系统";
			subTitle = "蓄电池电压";
			normalRange = "10~15V";
			knowledge = mContext.getResources().getString(R.string.text_battery_background_knowledge);
			curValue = String.format(Locale.getDefault(),"%.1fV", CarModel.getInstance().devModule.mVoltage / 1000.0);
			break;
		case R.id.system_air_intake:
			title = "进气系统";
			subTitle = "节气门开度";
			normalRange = "20.7%~27.6%";
			knowledge = mContext.getResources().getString(R.string.text_solar_term_door_opening_background_knowledge);
			curValue = String.format(Locale.getDefault(),"%.1f",CarModel.getInstance().devModule.mSolarTermDoor * 100 / 255.0) + "%";
			break;
		case R.id.system_idling:
			title = "怠速控制系统";
			subTitle = "发动机转速";
			normalRange = "650~984r/min";
			knowledge = mContext.getResources().getString(R.string.text_engine_speed_background_knowledge);
			curValue = String.format(Locale.getDefault(),"%dr/min", CarModel.getInstance().devModule.mRotate);
			break;
		case R.id.system_cooling:
			title = "冷却系统";
			subTitle = "水温";
			normalRange = "0~112℃";
			knowledge = mContext.getResources().getString(R.string.text_water_temperature_background_knowledge);
			curValue = String.format(Locale.getDefault(),"%d°C", CarModel.getInstance().devModule.mWaterTemperature - 40);
			break;
		case R.id.system_memissions:
			title = "排放系统";
			subTitle = "三元催化器温度";
			normalRange = "300~800℃";
			knowledge = mContext.getResources().getString(R.string.text_three_yuan_catalyst_temperature_background_knowledge);
			curValue = CarModel.getInstance().devModule.mMemission;
			break;
		case R.id.system_vin_code:
			title = "车辆身份系统";
			knowledge = mContext.getResources().getString(R.string.text_car_about_vin);
			toPageId = PageDefine.PAGE_CAR_CONDITION_VIN;
			break;
		}
		ViewModel.getIns().setViewProperty(R.id.car_condiction_title, title);
		ViewModel.getIns().setViewProperty(R.id.car_condiction_subtitle,subTitle);
		ViewModel.getIns().setViewProperty(R.id.normal_range_value,normalRange);
		ViewModel.getIns().setViewProperty(R.id.current_value,curValue);
		ViewModel.getIns().setViewProperty(R.id.car_condiction_knowledge,knowledge);
		ViewModel.getIns().jumpPage(toPageId);
	}

	boolean isMute = false;
	private void onMuteApp(){
		AudioManager manager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
		int volume  = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if(volume == 0){
			manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
		}else{
			manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
		}
		
		Log.i("volume", "music volume:"+volume);
	}
	
	
	 
	  public List<AppInfo> getAppInfos(){
		  return mAppInfos;
	  }
	  
	private void delayToStartLocation(){
		Handler msgHandler = SinjetApplication.getInstance().getMsgClient().getMsgHandler();
		if(msgHandler != null)
			msgHandler.sendEmptyMessageDelayed(CarAssistService.MSG_CHECK_NETWORK, 10000);
	}
	public void checkNetworkStartLocation(){
		if(isNetworkAvailable()){
			Log.i(tag, "isNetworkAvailable start location");
//			startLocation();
		}else{
			delayToStartLocation();
			Log.i(tag, "delayToStartLocation");
		}
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager mgr = (ConnectivityManager) mContext.getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}
	void onClkStrategy(int viewId){
		switch(viewId){
		case R.id.navi_strategy_avoid_highspeed:
			mSettings.mAvoidHighSpeed = (mSettings.mAvoidHighSpeed==1)?0:1;
			if(mSettings.mAvoidHighSpeed == 1 && mSettings.mHighSpeed==1){
				mSettings.mHighSpeed = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed, mSettings.mHighSpeed);
			}
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_avoid_highspeed, mSettings.mAvoidHighSpeed);
			break;
		case R.id.navi_strategy_congestion:
			mSettings.mCongestion = (mSettings.mCongestion == 1)?0:1;
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_congestion, mSettings.mCongestion);
			break;
		case R.id.navi_strategy_highspeed:
			mSettings.mHighSpeed = (mSettings.mHighSpeed==1)?0:1;
			if(mSettings.mHighSpeed==1 && mSettings.mAvoidHighSpeed == 1 ){
				mSettings.mAvoidHighSpeed = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_avoid_highspeed, mSettings.mAvoidHighSpeed);
			}
			if(mSettings.mHighSpeed ==1 && mSettings.mCost == 1){
				mSettings.mCost = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_cost, mSettings.mCost);
			}
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed, mSettings.mHighSpeed);
			break;
		case R.id.navi_strategy_cost:
			mSettings.mCost = (mSettings.mCost == 1)?0:1;
            if(mSettings.mCost == 1 && mSettings.mHighSpeed == 1){
            	mSettings.mHighSpeed = 0;
            	ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed,mSettings.mHighSpeed);
            }
            ViewModel.getIns().setViewProperty(R.id.navi_strategy_cost, mSettings.mCost);
			break;
		}
	}

	String mModuleCode = null;
	public void setModuleCode(String strCode) {
		if (mModuleCode == null || !mModuleCode.equals(strCode))
		{
			mModuleCode = strCode;
			uploadToServiceAnsy();
		}
	}
	int iModuleVersion = 0;
	public void setModuleVersion(int version) {
		if (iModuleVersion != version)
		{
			iModuleVersion = version;
			uploadToServiceAnsy();
		}
	}
	String mCarVIN = null;
	public void setCarVIN(String strVIN) {
		if (mCarVIN == null || !mCarVIN.equals(strVIN))
		{
			mCarVIN = strVIN;
			uploadToServiceAnsy();
		}
	}
	String mUsePlaceName = null;
	public void onGetLocation(String placeName) {
		if (mUsePlaceName == null || !mUsePlaceName.equals(placeName))
		{
			mUsePlaceName = placeName;
			uploadToServiceAnsy();
		}
	}
	
	String mAgencyCode = null;
	public String getAgencyCode() {
		return mAgencyCode;
	}
	
	public void setAgencyCode(String strCode) {
		if (mAgencyCode == null || !mAgencyCode.equals(strCode))
		{
			mAgencyCode = strCode;
			uploadToServiceAnsy();
		}
	}

	int ipcbVersion = 0;
	int iHUDAngleStorageAD = 0;
	int iHUDAngleNowAD = 0;
	public void setAxelaHUDHardwareInfo(int pcbVersion,int HUDAngleStorageAD,int HUDAngleNowAD) {
		boolean needPost = false;
		if (ipcbVersion != pcbVersion) {
			ipcbVersion = pcbVersion;
			needPost = true;
		}
		if (iHUDAngleStorageAD != HUDAngleStorageAD) {
			iHUDAngleStorageAD = HUDAngleStorageAD;
			needPost = true;
		}
		if (iHUDAngleNowAD != HUDAngleNowAD) {
			iHUDAngleNowAD = HUDAngleNowAD;
			needPost = true;
		}

		if (needPost) {
			uploadToServiceAnsy();			
		}
	}
	
	public void uploadToServiceAnsy(){
		if(!NaviModel.getInstance().isNetworkAvailable()) return;
		if (CarModel.getInstance().devModule.getMcuUUID() == null || CarModel.getInstance().devModule.getMcuUUID().isEmpty())
		{
			return;
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				String result = "-1";
				Map<String, String> appInfoMap = new HashMap<String,String>();
				appInfoMap.put("module_uuid", CarModel.getInstance().devModule.getMcuUUID());

				appInfoMap.put("user_phone", android.os.Build.MODEL);
				appInfoMap.put("phone_os", String.format("%d", android.os.Build.VERSION.SDK_INT));
				
				if (mAgencyCode != null)
				{
					appInfoMap.put("distributor_code", mAgencyCode);
				}
				if (mUsePlaceName != null)
				{
					appInfoMap.put("location_detail", mUsePlaceName);
				}
				if (mModuleCode != null)
				{
					appInfoMap.put("module_code", mModuleCode);
				}
				if (iModuleVersion > 0)
				{
					appInfoMap.put("mcu_version", String.format("%d", iModuleVersion));
				}
				
				if (ipcbVersion > 0)
				{
					appInfoMap.put("module_pcb_version", String.format("%d", ipcbVersion));
				}
				if (iHUDAngleStorageAD > 0 || iHUDAngleNowAD > 0)
				{
					appInfoMap.put("storage_open_ad", String.format("%d", iHUDAngleStorageAD));
					appInfoMap.put("now_open_ad", String.format("%d", iHUDAngleNowAD));
				}

				result = HttpUtils.submitPostData("https://sinjeterp.applinzi.com/axelaHUDHardware/", appInfoMap, "utf-8");
				//result = HttpUtils.submitPostData("http://192.168.1.110:8000/axelaHUDHardware/", appInfoMap, "utf-8");
				result = result.trim();
				if (result.equals("0"))
				{

				}
				Log.i("http", "app uuid result:"+result);					
			}
		}).start();
	}
	
}